package org.example.paymentservice.service.provider.impl;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.paymentservice.config.PaymentProperties;
import org.example.paymentservice.service.provider.PaymentProvider;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component("wechat_pay")
@RequiredArgsConstructor
public class WeChatPayProvider implements PaymentProvider {
    private final PaymentProperties paymentProperties;
    private final WXPay wxPay;

    @Override
    public String processPayment(BigDecimal amount, Map<String, String> paymentDetails) {
        try {
            Map<String, String> requestData = new HashMap<>();
            requestData.put("body", paymentDetails.get("description"));
            requestData.put("out_trade_no", paymentDetails.get("orderNo"));
            // 微信支付金额单位为分
            requestData.put("total_fee", String.valueOf(amount.multiply(new BigDecimal(100)).intValue()));
            requestData.put("spbill_create_ip", paymentDetails.get("clientIp"));
            requestData.put("notify_url", paymentProperties.getWechatPay().getNotifyUrl());
            requestData.put("trade_type", "JSAPI"); // 或者 "NATIVE", "APP" 等

            Map<String, String> response = wxPay.unifiedOrder(requestData);
            
            if ("SUCCESS".equals(response.get("return_code")) && "SUCCESS".equals(response.get("result_code"))) {
                return response.get("prepay_id");
            } else {
                throw new RuntimeException("WeChatPay unified order failed: " + response.get("err_code_des"));
            }
        } catch (Exception e) {
            log.error("WeChatPay payment processing failed", e);
            throw new RuntimeException("Payment processing failed", e);
        }
    }

    @Override
    public boolean validatePayment(String transactionId) {
        try {
            Map<String, String> requestData = new HashMap<>();
            requestData.put("out_trade_no", transactionId);

            Map<String, String> response = wxPay.orderQuery(requestData);
            
            return "SUCCESS".equals(response.get("return_code")) 
                && "SUCCESS".equals(response.get("result_code"))
                && "SUCCESS".equals(response.get("trade_state"));
        } catch (Exception e) {
            log.error("WeChatPay payment validation failed", e);
            return false;
        }
    }

    @Override
    public String processRefund(String transactionId, BigDecimal amount, String reason) {
        try {
            Map<String, String> requestData = new HashMap<>();
            requestData.put("out_trade_no", transactionId);
            requestData.put("out_refund_no", "REFUND_" + transactionId);
            // 微信支付金额单位为分
            requestData.put("total_fee", String.valueOf(amount.multiply(new BigDecimal(100)).intValue()));
            requestData.put("refund_fee", String.valueOf(amount.multiply(new BigDecimal(100)).intValue()));
            requestData.put("refund_desc", reason);

            Map<String, String> response = wxPay.refund(requestData);
            
            if ("SUCCESS".equals(response.get("return_code")) && "SUCCESS".equals(response.get("result_code"))) {
                return response.get("refund_id");
            } else {
                throw new RuntimeException("WeChatPay refund failed: " + response.get("err_code_des"));
            }
        } catch (Exception e) {
            log.error("WeChatPay refund processing failed", e);
            throw new RuntimeException("Refund processing failed", e);
        }
    }
}